package com.jdk.demo.nio.半包粘包.old;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NioSocketClient extends Thread {
	private SocketChannel socketChannel;
	private Selector selector = null;

	public static void main(String args[]) throws IOException {
		NioSocketClient client = new NioSocketClient();
		client.initClient();
		client.start();
	}

	public NioSocketClient() {
	}

	public void initClient() throws IOException {
		InetSocketAddress inetSocketAddress = new InetSocketAddress(8888);
		selector = Selector.open();
		socketChannel = SocketChannel.open();
		socketChannel.configureBlocking(false);
		socketChannel.connect(inetSocketAddress);
		synchronized (selector) {
			socketChannel.register(selector, SelectionKey.OP_CONNECT);
		}
	}

	public void run() {
		while (true) {
			try {
				int key = selector.select();
				if (key > 0) {
					Set<SelectionKey> keySet = selector.selectedKeys();
					Iterator<SelectionKey> iter = keySet.iterator();
					while (iter.hasNext()) {
						SelectionKey selectionKey = null;
						synchronized (iter) {
							selectionKey = iter.next();
							iter.remove();
						}

						if (selectionKey.isConnectable()) {
							finishConnect(selectionKey);
						}
						if (selectionKey.isWritable()) {
							send(selectionKey);
						}
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public void finishConnect(SelectionKey key) {
		System.out.println("client finish connect!");
		SocketChannel socketChannel = (SocketChannel) key.channel();
		try {
			socketChannel.finishConnect();
			synchronized (selector) {
				key.interestOps(SelectionKey.OP_WRITE);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void send(SelectionKey key) {
		SocketChannel channel = (SocketChannel) key.channel();

		for (int i = 0; i < 1; i++) {
			String ss = i + "Server ,how are you? this is package message from NioSocketClient!";
			ByteBuffer byteBuffer = ByteBuffer.wrap(ss.getBytes());

			System.out.println("[client] send:{" + i + "}-- " + ss);
			while (byteBuffer.hasRemaining()) {
				try {
					channel.write(byteBuffer);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		try {
			synchronized (selector) {
				channel.register(selector, SelectionKey.OP_READ);
			}
		} catch (ClosedChannelException e) {
			e.printStackTrace();
		}
	}

}
